package com.cxyd.modules.job.task.scanTask;

import com.cxyd.common.utils.ApiResult;
import com.cxyd.modules.wcs.dto.PostWmsDTO;
import com.cxyd.modules.wcs.service.PostWmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Component("post-wms")
@Slf4j
public class PostWmsTask {
    private final RestTemplate restTemplate;
    private final PostWmsService postWmsService;
    private final String wmsUrl = "http://localhost:8086/wms-admin/api/wcsCallback";
    //创建锁，防止并发情况出现
    private Lock lock = new ReentrantLock();

    public PostWmsTask(RestTemplate restTemplate, PostWmsService postWmsService) {
        this.restTemplate = restTemplate;
        this.postWmsService = postWmsService;
    }

    public void scanPost() {
        lock.lock();
        try {
            final PostWmsDTO record = postWmsService.getOneRecord();
            if (record == null) {
//                log.info("no post to wms...");
                return;
            }
            ApiResult respond = restTemplate.postForObject(wmsUrl, record, ApiResult.class);
            if (respond == null) {
                log.error("上位系统无响应!");
                return;
            }
            /*发送成功则处理数据*/
            if (respond.getRequestPk().length() == 0 || "404".equals(respond.getRequestPk())) {
                return;
            }
            postWmsService.postWmsHandle(record, respond);
        } catch (Exception e) {
            log.error("上报搬送指令异常，causeBy:{}", e.getMessage());
        } finally {
            lock.unlock();//释放锁
        }
    }
}
